package org.jcat.demo.mybatis;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jcat.demo.mybatis.mapper.AuthorMapper;
import org.jcat.demo.mybatis.mapper.BlogMapper;
import org.jcat.demo.mybatis.po.Author;
import org.jcat.demo.mybatis.po.Blog;

public class MyBatisTest {

	public static void main(String[] args) throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		SqlSession session = sqlSessionFactory.openSession();
		BlogMapper blogMapper = session.getMapper(BlogMapper.class);
		AuthorMapper authorMapper = session.getMapper(AuthorMapper.class);

		blogMapper.deleteAll();
		authorMapper.deleteAll();
		session.commit();


		Author a1 = new Author();
		a1.setId("1");
		a1.setName("张三");
		a1.setGender("男");
		a1.setAge(20);

		Author a2 = new Author();
		a2.setId("2");
		a2.setName("李四");
		a2.setGender("女");
		a2.setAge(30);


		authorMapper.add(a1);
		authorMapper.add(a2);



		//添加
		Blog b1 = new Blog();
		//b1.setId("1");	//ID自增
		b1.setName("Java从入门到放弃");
		b1.setAuthor(a1);


		Blog b2 = new Blog();
		//b1.setId("2");	//ID自增
		b2.setName("MySql从删库到跑路");
		b2.setAuthor(a2);

		blogMapper.addBlog(b1);
		blogMapper.addBlog(b2);
		session.commit();


		List<Blog> blogList = blogMapper.selectBlogList("Java%");
		System.out.println(blogList.size());
		
		
		List<Blog> blogList2 = blogMapper.selectAuthorBlogList("1");
		System.out.println("blogList2.size:" + blogList2.size());
		for (Blog blog2 : blogList2) {
			System.out.println(blog2.getAuthor().getId() + ", " + blog2.getAuthor().getName() + "," + blog2.getId() + ", " + blog2.getName());
		}
		
		
		blogMapper.deleteBlog("114");
		session.commit();
		session.close();

	}

}
